package com.maven.booksystem.config;


// 该类实现统一数据返回

import com.fasterxml.jackson.databind.ObjectMapper;
import com.maven.booksystem.model.ResultInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    ObjectMapper mapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 这里 是 用来 判断是否要进行 统一数据返回
        // 如果是 false ，就不处理，不执行 beforeBodyWrite 方法
        // 如果是 true ，就要进行处理 ，执行 beforeBodyWrite 方法
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof String){
            return mapper.writeValueAsString(ResultInfo.success(body));
        }
        if(body instanceof ResultInfo){
            return body;
        }
        return ResultInfo.success(body);
    }
}
